package com.dd.common.validator;

import com.dd.common.validator.annotation.ValidTimeRange;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.time.LocalDateTime;

/**
 * 时间范围校验器
 * @author ikun-cheng
 */
public class TimeRangeValidator implements ConstraintValidator<ValidTimeRange, Object> {

    private String startFieldName;
    private String endFieldName;

    @Override
    public void initialize(ValidTimeRange annotation) {
        this.startFieldName = annotation.start();
        this.endFieldName = annotation.end();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            Field startField = value.getClass().getDeclaredField(startFieldName);
            Field endField = value.getClass().getDeclaredField(endFieldName);

            startField.setAccessible(true);
            endField.setAccessible(true);

            Object startVal = startField.get(value);
            Object endVal = endField.get(value);

            if (startVal == null || endVal == null) {
                return true; // 允许为空，不校验
            }

            if (startVal instanceof LocalDateTime && endVal instanceof LocalDateTime) {
                return !((LocalDateTime) startVal).isAfter((LocalDateTime) endVal);
            }

            return true;
        } catch (Exception e) {
            // 反射失败也认为校验通过（开发阶段应避免字段名错误）
            return true;
        }
    }
}
